#include "autoupdate.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QVersionNumber>
#include <QTimer>
#include <QProgressDialog>
#include <QMessageBox>
#include <QApplication>
#include <QDir>
#include <QStandardPaths>
#include <QProcess>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>

AutoUpdateService::AutoUpdateService(QObject *parent)
    : QObject(parent)
    , networkManager(new QNetworkAccessManager(this))
    , currentVersion(QVersionNumber::fromString("1.0.0"))
    , autoCheck(true)
    , checkInterval(24) // 默认24小时检查一次
    , checkReply(nullptr)
    , downloadReply(nullptr)
    , checkTimer(new QTimer(this))
    , downloadDialog(nullptr)
{
    connect(checkTimer, &QTimer::timeout, this, &AutoUpdateService::onCheckTimerTimeout);
    
    // 默认启动定时器
    checkTimer->start(checkInterval * 60 * 60 * 1000); // 转换为毫秒
}

AutoUpdateService::~AutoUpdateService()
{
    if (checkReply) {
        checkReply->abort();
    }
    
    if (downloadReply) {
        downloadReply->abort();
    }
}

void AutoUpdateService::setApplicationInfo(const QString &name, const QString &version)
{
    applicationName = name;
    currentVersion = QVersionNumber::fromString(version);
}

void AutoUpdateService::setUpdateServerUrl(const QString &url)
{
    updateServerUrl = url;
}

void AutoUpdateService::setCheckInterval(int hours)
{
    checkInterval = hours;
    checkTimer->setInterval(checkInterval * 60 * 60 * 1000);
}

void AutoUpdateService::checkForUpdates()
{
    startUpdateCheck();
}

void AutoUpdateService::setAutoCheck(bool autoCheck)
{
    this->autoCheck = autoCheck;
    
    if (autoCheck) {
        if (!checkTimer->isActive()) {
            checkTimer->start();
        }
    } else {
        checkTimer->stop();
    }
}

bool AutoUpdateService::isAutoCheck() const
{
    return autoCheck;
}

void AutoUpdateService::downloadUpdate(const QString &downloadUrl)
{
    Q_UNUSED(downloadUrl)
    // 开始下载更新
    QMessageBox::information(nullptr, tr("下载更新"), tr("更新下载功能将在完整实现中提供"));
}

void AutoUpdateService::installUpdate(const QString &installerPath)
{
    Q_UNUSED(installerPath)
    // 安装更新
    QMessageBox::information(nullptr, tr("安装更新"), tr("更新安装功能将在完整实现中提供"));
}

void AutoUpdateService::onCheckUpdateFinished()
{
    if (!checkReply)
        return;
        
    checkReply->deleteLater();
    
    if (checkReply->error() != QNetworkReply::NoError) {
        emit updateCheckError(checkReply->errorString());
        return;
    }
    
    QByteArray data = checkReply->readAll();
    parseUpdateInfo(data);
}

void AutoUpdateService::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    Q_UNUSED(bytesReceived)
    Q_UNUSED(bytesTotal)
    // 更新下载进度
}

void AutoUpdateService::onDownloadFinished()
{
    if (!downloadReply)
        return;
        
    downloadReply->deleteLater();
    
    if (downloadReply->error() != QNetworkReply::NoError) {
        emit updateDownloadError(downloadReply->errorString());
        return;
    }
    
    // 保存下载的文件
    QByteArray data = downloadReply->readAll();
    QString tempPath = QDir::tempPath() + "/" + applicationName + "_update.exe";
    
    QFile file(tempPath);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        emit updateDownloaded(tempPath);
    } else {
        emit updateDownloadError(tr("无法保存更新文件"));
    }
}

void AutoUpdateService::onCheckTimerTimeout()
{
    if (autoCheck) {
        startUpdateCheck();
    }
}

void AutoUpdateService::startUpdateCheck()
{
    if (updateServerUrl.isEmpty()) {
        emit updateCheckError(tr("未设置更新服务器URL"));
        return;
    }
    
    QNetworkRequest request;
    request.setUrl(QUrl(updateServerUrl));
    
    checkReply = networkManager->get(request);
    connect(checkReply, &QNetworkReply::finished, this, &AutoUpdateService::onCheckUpdateFinished);
}

void AutoUpdateService::parseUpdateInfo(const QByteArray &data)
{
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        emit updateCheckError(tr("解析更新信息失败: %1").arg(parseError.errorString()));
        return;
    }
    
    if (!doc.isObject()) {
        emit updateCheckError(tr("无效的更新信息格式"));
        return;
    }
    
    QJsonObject obj = doc.object();
    QString version = obj.value("version").toString();
    QString changelog = obj.value("changelog").toString();
    downloadUrl = obj.value("download_url").toString();
    
    if (isVersionNewer(version)) {
        latestVersion = version;
        emit updateAvailable(version, changelog);
    } else {
        emit noUpdateAvailable();
    }
}

bool AutoUpdateService::isVersionNewer(const QString &version) const
{
    QVersionNumber newVersion = QVersionNumber::fromString(version);
    return newVersion > currentVersion;
}